<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>搜索排序</title>
    <script src="js/vue.js"></script>
</head>
<body>
    <div id="demo">
        <input type="text" v-model="searchName">
        <ul>
            <li v-for="(p, index) in filterPersons" :key="index">
                {{index}}--{{p.name}}--{{p.age}}
            </li>
        </ul>
        <button @click="setType(1)">按年龄升序</button>
        <button @click="setType(2)">按年龄降序</button>
        <button @click="setType(3)">按原本顺序</button>
    </div>
<script>
    let app = new Vue({
        el: "#demo",
        data: {
            searchName: "",
            orderType: 1, //排序类型 1: 升序， 2： 降序 3： 原本
            persons: [
                {name: "Bob", age: 28},
                {name: "Lily", age: 18},
                {name: "Mary", age: 25},
                {name: "Tom", age: 23}
            ]
        },
        computed: {
            filterPersons(){
                const {searchName, persons} = this;
                //过滤数组
                let result = persons.filter(item=>{
                    return item.name.indexOf(searchName)!==-1;
                });

                //排序
                if(this.orderType != 3){
                    let orderType = this.orderType;
                    result.sort(function (p1, p2) {
                        if(orderType === 1){
                            return p1.age - p2.age; //升序
                        }
                        return p2.age - p1.age; //降序
                    });
                }
               return result;
            }
        },
        methods:{
            setType(type){
                this.orderType = type;
            }
        }
    });
</script>
</body>
</html>